import { Graph } from '@antv/x6'
import { InitGraphOption } from './type'
import { Scroller } from '@antv/x6-plugin-scroller'
import { Selection } from '@antv/x6-plugin-selection'
import { initBasicsGraphOptions } from '@yk/components/draw/editor-draw/utils'
import { graphOptions } from '@yk/components/draw/show-draw/config'

export function initGraph (options: InitGraphOption) {
  const graph = initBasicsGraphOptions(options, graphOptions)
  // 注册绘制时所需事件
  bindDrawingEvent(graph)
  options.json.cells && drawingGraph(graph, options.json)
  return graph
}

// region TODO 注册事件
function bindDrawingEvent (graph: Graph) {
  graph.on('cell:added', ({ cell }) => {
    const events = cell?.data?.events
    if (events) events?.added && events?.added(graph, { cell, isEdit: true })
  })
  document.onkeyup = function () {
    const scroller: Scroller = graph.getPlugin('scroller')
    const selection: Selection = graph.getPlugin('selection')
    scroller.disablePanning()
    selection.enableRubberband()
  }
}
// endregion

/**
 * 根据JSON绘制内容
 * @param graph
 * @param json
 */
export function drawingGraph (graph: Graph, json: Record<string, any>) {
  graph.fromJSON(json)
  // const { container } = graph.options
  // container.style.backgroundColor = json.backgroundColor
  // container.style.backgroundImage = `url(${json.backgroundImage})`
  // const options = graph.options as any
  // options.backgroundImage = json.backgroundImage
  // options.size = {
  //   width: json.width,
  //   height: json.height
  // }
  // bindConfig(graph, graph.getCells())
}
